#!/usr/bin/perl
use FindBin;
use lib "$FindBin::Bin/../pllib/lib/perl5";
use lib "$FindBin::Bin/../lib";

use strict;
use POSIX qw(strftime);
use IO::File;
use JSON;
use Getopt::Long;

sub usage {
    my $pname = $FindBin::Script;

    print("$pname --filename <profile file name> --content  <environment content>\n");
    exit(1);
}

sub main {
    my $user;
    my $fileName;
    my $content;

    GetOptions(
        'user=s'     => \$user,
        'filename=s' => \$fileName,
        'content=s'  => \$content
    );

    if ( not defined($content) or $content eq '' ) {
        print("ERROR: Must defined modify content by option --content\n");
        usage();
    }

    my $uid = $<;

    if ( defined($user) and $user ne '' ) {
        my $curUid  = $<;
        my $curUser = getpwuid($<);
        if ( $curUser ne $user ) {
            if ( $curUid ne 0 ) {
                print("ERROR: Can not generate user:$user ssh-key by user:$curUser.\n");
                exit(3);
            }
        }
    }
    else {
        $user = getpwuid($uid);
    }

    my @userInfo = getpwnam($user);
    my $homePath = $userInfo[7];
    my $uid      = $userInfo[2];
    my $gid      = $userInfo[3];
    my $group    = getgrgid($gid);

    my $filePath = "$homePath/$fileName";

    my $hasError = 0;

    my $exportMap  = {};
    my $confMap    = {};
    my $noneEnvMap = {};
    my @keysArray  = ();
    $content =~ s/\\n/\n/sg;

    foreach my $line ( split( /\n/, $content ) ) {
        $line =~ s/^\s*|\s*$//g;
        my ( $key, $val ) = split( /\s*=\s*/, $line, 2 );
        if ( $key =~ s/^export\s+// ) {
            $exportMap->{$key} = 1;
        }
        if ( index( $line, '=' ) > 0 ) {
            if ( defined($val) ) {
                $confMap->{$key} = $val;
            }
            else {
                $confMap->{$key} = '';
            }
        }
        else {
            $noneEnvMap->{$key} = '';
        }

        push( @keysArray, $key );
    }

    my $keyProcessedMap = {};
    my $isChanged       = 0;
    my $newContent      = '';
    my $fh              = IO::File->new( $filePath, 'a+' );
    if ( defined($fh) ) {
        $fh->seek( 0, 0 );
        my $line;
        while ( $line = $fh->getline() ) {
            if ( $line !~ /^\s*$/ and $line !~ /^\s*#/ ) {
                my $tmpLine = $line;
                $tmpLine =~ s/^\s*|\s*$//g;

                my ( $key, $val ) = split( /\s*=\s*/, $tmpLine, 2 );

                my $hasExport = 0;
                if ( $key =~ s/^export\s+// ) {
                    $hasExport = 1;
                }

                my $newVal = $confMap->{$key};
                if ( defined($newVal) ) {

                    #delete( $confMap->{$key} );
                    $keyProcessedMap->{$key} = 1;
                    if ( $newVal ne $val ) {
                        $isChanged = 1;
                        $line =~ s/=.*$/=$newVal/;
                        if ( $hasExport == 0 and $exportMap->{$key} ) {
                            $line = "export $line";
                        }
                        print("Replace: $tmpLine -> $line");
                    }
                    else {
                        if ( $hasExport == 0 and $exportMap->{$key} ) {
                            $isChanged = 1;
                            $line      = "export $line";
                            print("Replace: $tmpLine -> $line");
                        }
                        else {
                            print("NotChanged: $line");
                        }
                    }
                }
                elsif ( defined( $noneEnvMap->{$key} ) ) {
                    $keyProcessedMap->{$key} = 1;
                    print("NotChanged: $line");
                }
            }
            $newContent = $newContent . $line;
        }

        foreach my $key (@keysArray) {
            if ( $keyProcessedMap->{$key} == 1 ) {
                next;
            }

            my $val = $confMap->{$key};

            $isChanged = 1;
            if ( $exportMap->{$key} ) {
                $newContent = $newContent . "export $key=$val\n";
                print("Append: export $key=$val\n");
            }
            else {
                if ( defined($val) ) {
                    $newContent = $newContent . "$key=$val\n";
                    print("Append: $key=$val\n");
                }
                else {
                    $newContent = $newContent . "$key\n";
                    print("Append: $key\n");
                }
            }
        }

        if ( $isChanged == 1 ) {
            if ( $hasError == 0 ) {
                $fh->seek( 0, 0 );
                $fh->truncate(0);
                $fh->write( $newContent, length($newContent) );
            }
        }

        $fh->close();
    }
    else {
        $hasError = 1;
        print("ERROR: Can not open file:$filePath, $!\n");
    }

    if ( not chown( $uid, $gid, $filePath ) ) {
        $hasError = 1;
        print("ERROR: Can not change file $filePath owner to $user:$group, $!.\n");
    }

    return $hasError;
}

exit main();
